package chances.epg.navigator.history;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import chances.epg.navigator.EpgConstants;
import chances.epg.navigator.controller.AjaxReqController;
import chances.epg.play.ctrl.PlayController;
import chances.epg.session.UserSession;
import chances.epg.session.UserSessionHelper;
import chances.epg.session.ctrl.LogonController;

public class UserAccessStackInterceptor extends HandlerInterceptorAdapter {
	
	final static String[] excludeParams = new String[]{EpgConstants.LEAVE_FOCUS_ID,"return","stb_type","user_id","domain","sign"};
	final static String[] includeParams = new String[]{EpgConstants.ENTRY_FOCUS_ID, "ps","p_idx"};

	static Log accessStackLog = LogFactory.getLog("UserAccessStack");
	private String privUrlName = "cs_privUrl";
	private String focusName = EpgConstants.LEAVE_FOCUS_ID;
	private String enterFocus = EpgConstants.ENTRY_FOCUS_ID;
	private String entryName = "privEntry";
	private boolean enable = true;
	private boolean cookieEnable = false;

	private String returnParameterName = "return";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!enable) {
			return true;
		}
		UserSession userSession = UserSessionHelper.getUserSession(request);
		if (userSession == null) {
			return true;
		}
		String privUrl = null;
		String returnUrl = request.getParameter("return");
		UserAccessStack stack = UserAccessStack.findUserAccessStack(request);
		if (StringUtils.isNotEmpty(returnUrl)) {
			userSession.setReturnUrl(returnUrl);
			stack.clear();
			privUrl = userSession.getReturnUrl();
		}
		request.setAttribute("accessStack", stack);
		UserAccessEntry curEntry = stack.createUserAccessEntry(request);
		stack.pop(curEntry);
		accessStackLog.info("statck pop: " + curEntry.getFullPath());
		UserAccessEntry lastEntry = stack.getLast();
		if (lastEntry != null && lastEntry.getPath() != null) {
			accessStackLog.info("lastEntry: " + lastEntry.getFullPath());
			addFocusParam(request, lastEntry);
			privUrl = lastEntry.getFullPath();
			request.setAttribute(entryName, lastEntry);

		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (ex == null) {
			UserAccessStack stack = UserAccessStack.findUserAccessStack(request);
			if (!isExclude(request, handler)) {
				UserAccessEntry entry = stack.add(request);
				accessStackLog.info("add stack " + entry.getFullPath());
			}
		}
	}

	private boolean isExclude(HttpServletRequest request, Object handler) {
		if (HandlerMethod.class.isInstance(handler)) {
			HandlerMethod aHanlderMeethod = (HandlerMethod) handler;
			if (LogonController.class.isInstance(aHanlderMeethod.getBean())
					|| PlayController.class.isInstance(aHanlderMeethod.getBean())
					|| AjaxReqController.class.isInstance(aHanlderMeethod.getBean())) {
				return true;
			}
		}
		return false;
	}
	/*
	 * private boolean isAddStack(HttpServletRequest request, Object handler) {
	 * boolean isAdd =
	 * ServletUtils.getBoolValue(request,rememberHistoryName,true); Boolean
	 * addStack = (Boolean) request.getAttribute("addStack");
	 * if(addStack!=null){ isAdd = addStack.booleanValue(); } if(isAdd){ return
	 * !(PlayerController.class.isInstance(handler)); }else{ return false; } }
	 */

	private void addFocusParam(HttpServletRequest request, UserAccessEntry lastEntry) {
		
		String focusId = request.getParameter(focusName);

		if (StringUtils.isNotEmpty(focusId)) {
			lastEntry.addParam(enterFocus, focusId);
		}
	}

	public String getPrivUrlName() {
		return privUrlName;
	}

	public void setPrivUrlName(String privUrlName) {
		this.privUrlName = privUrlName;
	}

	public String getFocusName() {
		return focusName;
	}

	public void setFocusName(String focusName) {
		this.focusName = focusName;
	}

	public String getEnterFocus() {
		return enterFocus;
	}

	public void setEnterFocus(String enterFocus) {
		this.enterFocus = enterFocus;
	}

	public String getEntryName() {
		return entryName;
	}

	public void setEntryName(String entryName) {
		this.entryName = entryName;
	}

	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}

	public boolean getCookieEnable() {
		return cookieEnable;
	}

	public void setCookieEnable(boolean cookieEnable) {
		this.cookieEnable = cookieEnable;
	}

	public String getReturnParameterName() {
		return returnParameterName;
	}

	public void setReturnParameterName(String returnParameterName) {
		this.returnParameterName = returnParameterName;
	}
}
